<template>
  <div class="specialDetail-container">
    <el-form
      ref="formRef"
      class="form-container"
      label-position="left"
      label-width="120px"
      :model="detail"
      :rules="rules"
    >
      <el-form-item :label="translate('单号') + '：'" prop="SPNo">
        <el-input v-model="detail.SPNo" style="width: 350px" />
      </el-form-item>
      <el-form-item :label="translate('名称') + '：'" prop="FullName">
        <el-input v-model="detail.FullName" style="width: 350px" />
      </el-form-item>
      <el-form-item :label="translate('编码') + '：'" prop="Code">
        <el-input v-model="detail.Code" style="width: 350px" />
      </el-form-item>
      <el-form-item :label="translate('日期') + '：'" prop="SPDate">
        <el-date-picker
          v-model="detail.SPDate"
          :clearable="false"
          style="width: 200px"
          type="datetime"
        />
      </el-form-item>
      <el-form-item :label="translate('单据状态') + '：'">
        <el-radio-group v-model="detail.SPStatus">
          <el-radio :label="0">{{ translate('待执行') }}</el-radio>
          <el-radio :label="1">{{ translate('已执行') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="translate('开始结束时间') + '：'" prop="times">
        <div style="width: 164px">
          <el-date-picker
            v-model="times"
            :clearable="false"
            :disabled-date="disabledDate"
            :end-placeholder="translate('结束时间')"
            range-separator="-"
            :start-placeholder="translate('开始时间')"
            type="datetimerange"
          />
        </div>
      </el-form-item>
      <!-- <el-form-item :label="translate('每周星期') + '：'">
        <el-checkbox-group v-model="weeks">
          <template v-for="(item, index) in weeksList" :key="index">
            <el-checkbox :label="item" />
          </template>
        </el-checkbox-group>
        <span class="ml20">{{ translate('生效') }}</span>
      </el-form-item> -->
      <el-form-item :label="translate('备注') + '：'">
        <el-input
          v-model="detail.Remark"
          prop="innerCode"
          style="width: 350px"
        />
      </el-form-item>
      <el-form-item :label="translate('商品') + '：'">
        <ProList v-model="proList" :spm-id="id || ''" />
      </el-form-item>
    </el-form>
    <div class="btns">
      <ElButton class="btn mr20" type="primary" @click="save">
        {{ translate('保存') }}
      </ElButton>
      <ElButton class="btn" @click="cancel">{{ translate('取消') }}</ElButton>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import {
    SpecialPriceGetDetailPageData,
    SpecialPriceUpdateData,
    SpecialPriceAddData,
  } from '@/api/mupro'
  import router from '@/router'
  import ProList from './components/proList.vue'
  import { parseTime } from '@/utils'
  import { translate } from '@/i18n'
  const rules = reactive({
    SPNo: [
      {
        required: true,
        trigger: 'blur',
        message: translate('请输入单号'),
      },
    ],
    FullName: [
      {
        required: true,
        trigger: 'blur',
        message: translate('请输入名称'),
      },
    ],
    Code: [
      {
        required: true,
        trigger: 'blur',
        message: translate('请输入编码'),
      },
    ],
    SPDate: [
      {
        required: true,
        trigger: 'blur',
        message: translate('请选择日期'),
      },
    ],
  })
  const route = useRoute()
  const id: any = ref('')
  const init = async () => {
    if (route.query && route.query.ID) {
      id.value = route.query.ID
    }
  }
  // 当天零点时间
  const getDay = () => {
    return new Date(new Date().setHours(0, 0, 0, 0))
  }
  const detail: any = ref({
    SPDate: getDay(),
    SPStatus: 0,
  })
  const proList: any = ref([])
  const times: any = ref([
    getDay(),
    new Date(new Date().setHours(23, 59, 59, 0)),
  ])
  // 小于当天时间不可选
  const disabledDate = (time: Date) => {
    return getDay().getTime() > time.getTime()
  }
  const weeksList = [
    translate('一'),
    translate('二'),
    translate('三'),
    translate('四'),
    translate('五'),
    translate('六'),
    translate('日'),
  ]
  const weeks = ref([])
  let originProList: any = []
  const getDetail = async () => {
    const { master, rows } = await SpecialPriceGetDetailPageData({
      value: id.value,
    })
    detail.value = master
    proList.value = rows
    originProList = [].concat(rows)
    times.value = [master.StartDate, master.EndDate]
    if (master.Weeks && master.Weeks.length) {
      weeks.value = master.Weeks.split(',')
    }
  }
  init().then(() => {
    if (id.value && id.value !== '0') {
      getDetail()
    }
  })
  const formRef: any = ref(null)
  const save = async () => {
    await formRef.value.validate(async (valid: any) => {
      if (valid) {
        if (proList.value.length === 0) {
          ElMessage({
            message: translate(`请选择至少一个商品`),
            type: 'warning',
          })
          return
        }
        detail.value.SPDate = parseTime(
          detail.value.SPDate,
          '{y}-{m}-{d} {h}:{i}:{s}'
        )
        detail.value.StartDate = parseTime(
          times.value[0],
          '{y}-{m}-{d} {h}:{i}:{s}'
        )
        detail.value.EndDate = parseTime(
          times.value[1],
          '{y}-{m}-{d} {h}:{i}:{s}'
        )
        detail.value.Weeks = weeks.value.join(',')
        const params: any = {
          mainData: detail.value,
          detailData: proList.value,
        }
        if (originProList.length > 0) {
          const originKeys = originProList.map((item: any) => item.SPBDId)
          const proListKeys = proList.value.map((item: any) => {
            if (item.SPBDId) return item.SPBDId
          })
          const delKeys: any = []
          originKeys.map((item: any) => {
            if (proListKeys.indexOf(item) === -1) {
              delKeys.push(item)
            }
          })
          console.log(delKeys)
          if (delKeys.length) {
            params.delKeys = delKeys
          }
        }
        let result: any = {}
        if (id.value) {
          result = await SpecialPriceUpdateData(params)
        } else {
          result = await SpecialPriceAddData(params)
        }
        const { code, data } = result
        if (code == 200) {
          router.back()
        }
      }
    })
  }
  const cancel = () => {
    router.back()
  }
</script>

<style lang="scss" scoped>
  .specialDetail-container {
    .form-container {
      // display: flex;
      // justify-content: space-around;

      .form-item {
        width: 40%;
        padding: 14px 20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.12);
      }

      .ml20 {
        margin-left: 20px;
      }
    }
    .btns {
      display: flex;
      justify-content: center;
      margin-top: 30px;

      .mr20 {
        margin-right: 10px;
      }
    }
  }
</style>
